package algorithm.lru;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * https://blog.csdn.net/u010947534/article/details/89092734
 * @param <K>
 * @param <V>
 */
public class HashMapLRU<K,V>{
    private LinkedHashMap<K, V> map;
    private int cacheSize;

    public HashMapLRU(int cacheSize) {
        this.cacheSize = cacheSize;
        map = new LinkedHashMap<K, V>(16,0.75f,true){
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                if(map.size() < cacheSize + 1 ) {
                    return false;
                }
                return true;
            }
        };
    }

    public synchronized V get(K k) {
        return map.get(k);
    }

    public synchronized void put(K k, V v) {
        map.put(k,v);
    }

    public void print() {
        for(Map.Entry<K, V> entry : map.entrySet()) {
            System.out.print(entry.getValue() + "--");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        HashMapLRU lru = new HashMapLRU(3);
        lru.put("key1",1);
        lru.put("key2",2);
        lru.get("key1");
        lru.put("key3",3);
        lru.print();
        lru.put("key4",4);
        lru.print();
    }
}
